package net.tv90.auth.controller;

import jakarta.security.auth.message.AuthException;
import net.tv90.auth.aop.annotation.AccessLimit;
import net.tv90.auth.service.UserService;
import net.tv90.auth.service.VerifyService;
import net.tv90.auth.utils.web.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

/**
 * 身份校验Controller，在其他服务器中配置拦截器指向该URL，
 * 如果在 http://baidu.com 请求身份认证，格式为 http://localhost:8080/verify?token=${token}&url=${url}
 * 由于是跨域请求，请求头中可以不携带 token
 *
 * @author TV90
 */
@RestController
@CrossOrigin
@RequestMapping("/verify")
@Validated
public class VerifyController {

    @Autowired
    VerifyService verifyService;

    @Autowired
    UserService userService;

    @AccessLimit(seconds = 5, maxCount = 15)
    @GetMapping
    public Result verify(@RequestParam String token, @RequestParam("url") String baseUrl) throws AuthException {
        Integer role = verifyService.checkVerified(token, baseUrl);
        if(role != null){
            return Result.success(role);
        } else {
            throw new AuthException("认证失败");
        }
    }

    @AccessLimit(seconds = 5, maxCount = 15)
    @GetMapping("/code")
    public Result getCode(@RequestParam String username) {
        String code = userService.getCode(username);
        if(code == null) {
            return Result.failed("该用户未认证");
        } else {
            return Result.success(code);
        }
    }
}
